package com.jic.manager.controller.manage.merchant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.conf.api.manage.SysConfigApi;
import com.jic.conf.request.SysConfigRequest;
import com.jic.conf.response.SysConfigResponse;
import com.jic.manager.api.rest.ManagerMerchantApi;
import com.jic.manager.entity.*;
import com.jic.manager.enums.DeptTypeEnum;
import com.jic.manager.request.MerchantImportRequest;
import com.jic.manager.request.MerchantRequest;
import com.jic.manager.request.MerchantReviewRequest;
import com.jic.manager.response.MerchantResponse;
import com.jic.manager.service.*;
import com.jic.manager.utils.BeanUtil;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.SaveProductRequest;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家控制器
 * @autho wwb
 */
@RestController
@RequestMapping("merchant")
@Slf4j
public class MerchantController  implements ManagerMerchantApi{

    @Resource
    private MerchantService mMerchantService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    ProductListApi productListApi;
    @Resource
    private MestoreService memStoreService;
    @Resource
    private SysConfigApi sysConfigApi;
    @Resource
    private SysRoleUserService sysRoleUserService;
    @Resource
    private SysConfigService sysConfigService;


    //查询列表
    @PostMapping(value = "/queryMerchantInfo")
    public RestResult<Merchant> queryInfo(@RequestBody Merchant merchant){
        Merchant merchantVo  = mMerchantService.queryByPrimaryKey(merchant.getId());
        return RestResult.success(merchantVo);
    }

    //查询列表
    @PostMapping(value = "/queryMerchantListOther")
    public RestResult<List<Merchant>> queryMerchantListOther(@RequestBody Merchant merchant){
        if(merchant.getAdminOperate().getDeptType().getCode()!=0){
            merchant.setDeptId(merchant.getAdminOperate().getDeptId());
        }
        List<Merchant> merchants  = mMerchantService.query(merchant);
        return RestResult.success(merchants);
    }

    //查询列表
    @PostMapping(value = "/queryMerchantList")
    public RestResult<PageResult<Merchant>> queryMerchantList(@RequestBody MerchantRequest merchantRequest){
        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(merchantRequest,merchant);
        PageResult<Merchant> merchantPageResult = mMerchantService.queryPage(merchant, new Page() {{
            setStart(merchantRequest.getStart());
            setLimit(merchantRequest.getLimit());
        }});
        return RestResult.success(merchantPageResult);
    }
    //编辑方法
    @PostMapping(value = "/editMerchantInfo")
    public RestResult editMerchantInfo(@RequestBody MerchantRequest merchantRequest){
        //是否继承平台商品
        if(merchantRequest.getIsAccept() !=null && merchantRequest.getIsAccept() == 1){
            SaveProductRequest productInfoRequest=new SaveProductRequest();
            if (merchantRequest.getId() != null ){
                productInfoRequest.setDeptId(merchantRequest.getId());
                productListApi.saveMerchantProduct(productInfoRequest);
            }
        }
        return mMerchantService.editMerchantInfo(merchantRequest);
    }

    /*
    *  商家入驻
    * */
    @PostMapping(value = "merchantsSettled")
    public RestResult<String> merchantsSettled(@RequestBody MerchantRequest merchantRequest){
        try {
            return mMerchantService.merchantsSettled(merchantRequest);
        }catch (Exception e){
            log.error("error",e);
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }


    /**
     * 商家审核
     * @param merchantReviewRequest
     * @return
     */
    @PostMapping(value = "merchantReview")
    public RestResult<String> merchantReview(@RequestBody MerchantReviewRequest merchantReviewRequest){
        try {
            String idsStr = merchantReviewRequest.getIds();
            String toStatus = merchantReviewRequest.getStatus();
            if (StringUtils.isEmpty(idsStr)){
                throw new Exception("请选择要审核的商家");
            }
            String[] idsList = idsStr.split(",");


            //查询conf配置
            RestResult<List<SysConfigResponse>> infoByKey = new RestResult<List<SysConfigResponse>>();
            SysConfigRequest sysConfigRequest = new SysConfigRequest();
            sysConfigRequest.setIds("300,301");
            SysConfig sysconfig =  BeanUtil.copy(sysConfigRequest,SysConfig.class);
            sysconfig.setKey(sysConfigRequest.getKeys());
            sysconfig.setIds(sysConfigRequest.getIds());
            List<SysConfig> sysConfig= sysConfigService.query(sysconfig);
            List<SysConfigResponse> sysConfigResponses = JSON.parseArray(JSON.toJSONString(sysConfig), SysConfigResponse.class);
            infoByKey=RestResult.success(sysConfigResponses);

            List<SysConfigResponse> configList = infoByKey.getData();
            SysConfigResponse baseDeptInfo = configList.stream().filter(config -> config.getId() == 300L).collect(Collectors.toList()).get(0);
            SysConfigResponse baseMerchantInfo = configList.stream().filter(config -> config.getId() == 301L).collect(Collectors.toList()).get(0);

            for (int i = 0; i < idsList.length; i++) {
                Long id = Long.valueOf(idsList[i]);
                Merchant mMerchant = mMerchantService.queryByPrimaryKey(id);
                if (mMerchant == null || mMerchant.getDeleteFlag() == 1){
                    throw new Exception("当前商家不存在");
                }
                int status = mMerchant.getStatus().intValue();
                if (status != 1) {
                    throw new Exception("当前商家状态不是未审核 name="+mMerchant.getName());
                }

                Long deptId = null;

                if (!toStatus.equals("3")){
                    //审核成功 增加组织架构
                    deptId = sysDeptService.insertSysDept(new SysDept(){{
                        setDeptName(mMerchant.getName());
                        setPid(Long.valueOf(baseDeptInfo.getVal()));
                        setBusinessId(mMerchant.getId());
                        setDeptType(DeptTypeEnum.MERCHANT_TYPE.getType());
                        setStatus("0");
                        setCreateTime(new Date());
                        setCreator(merchantReviewRequest.getAdminOperate().getOperator());
                        setDeleteFlag(0);
                    }});
                }
                Long finalDeptId = deptId;
                mMerchantService.update(new Merchant(){{
                    setDeptId(finalDeptId);
                    setId(mMerchant.getId());
                    setStatus(Integer.valueOf(toStatus));
                    if (toStatus.equals("3")){
                        //审核拒绝
//                        String reviewReason = paramAsDto.getAsString("reviewReason");
                        String reviewReason = merchantReviewRequest.getReviewReason();
                        if (StringUtils.isEmpty(reviewReason)) {
                            throw new Exception("审核拒绝时,审核理由必填");
                        }
                        setReviewReason(reviewReason);
                    }
                    setUpdateTime(new Date());
                }});
                SysUser sysUser = sysUserService.queryByPrimaryKey(mMerchant.getUserId());
                if (sysUser == null || sysUser.getDeleteFlag().equals(1)) {
                    throw new Exception("当前商家不存在账号");
                }
                sysUserService.update(new SysUser(){{
                    setRoleid(sysUser.getRoleid() != null ? sysUser.getRoleid() : Long.valueOf(baseMerchantInfo.getVal()));
                    setLname(finalDeptId != null ? mMerchant.getName() : null);
                    setDeptId(finalDeptId);
                    setId(sysUser.getId());
                    setUpdateTime(new Date());
                    if (toStatus.equals("2")){
                        setStatus(1);
                    }else{
                        setStatus(0);
                    }
                }});

                if(sysUser.getRoleid() == null){
                    sysRoleUserService.insert(new SysRoleUser(){{
                        setStatus("0");
                        setRoleid(Long.valueOf(baseMerchantInfo.getVal()));
                        setUserid(sysUser.getId());
                    }});
                }
            }
            return RestResult.success("成功");
        }catch (Exception e){
            log.error("商家审核错误====>>>>>>>>>>>>>>>>>>>>>{}",e);
            return RestResult.error("9999",e.getLocalizedMessage());
        }
    }


//    @ApiOperation(value = "分页查询商家列表信息")
//    @PostMapping(value = "/queryMerchantList")
//    public RestResult<PageResult<Merchant>> queryMerchantPage(@RequestBody MerchantRequest merchantRequest){
//        RestResult result = new RestResult();
//        Merchant merchant = new Merchant();
//        BeanUtils.copyProperties(merchantRequest,merchant);
//        // 获取用户权限
//        AdminOperate adminOperate=merchantRequest.getAdminOperate();
//        //如果是店铺登录 查询店铺所属商家ids
//        if (adminOperate.getDeptType().getCode() == 3){
//            Mestore mesQuery = new Mestore();
//            mesQuery.setId(adminOperate.getBusinessId());
//            List<Mestore> mestores  = memStoreService.query(mesQuery);
//            List<Long>merchantList=new ArrayList<> ();
//            merchantList.add(mestores.get(0).getMerchantId());
//            merchant.setMerchantIds(merchantList);
//        }else{
//            if (null == adminOperate.getMerchantIds() || adminOperate.getMerchantIds().size()==0){
//                result.setCode("0000");
//                result.setMsg("暂无数据");
//                return result;
//            }
//            merchant.setMerchantIds(adminOperate.getMerchantIds());
//        }
//
//        PageResult<Merchant> merchantPageResult = mMerchantService.queryMerchantPage(merchant, new Page() {{
//            setStart(merchantRequest.getStart());
//            setLimit(merchantRequest.getLimit());
//        }});
//        return RestResult.success(merchantPageResult);
//    }


    @ApiOperation(value = "查询商家列表信息")
    @PostMapping(value = "/queryMerchantPageOther")
    public RestResult<List<Merchant>> queryMerchantPageOther(@RequestBody MerchantRequest merchantRequest){
        RestResult result = new RestResult();
        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(merchantRequest,merchant);
        // 获取用户权限
        AdminOperate adminOperate=merchantRequest.getAdminOperate();
        if (null == adminOperate.getMerchantIds() || adminOperate.getMerchantIds().size()==0){
            result.setCode("0000");
            result.setMsg("暂无数据");
            return result;
        }
        merchant.setDeptIds(adminOperate.getMerchantIds());
        List<Merchant> merchants  = mMerchantService.queryMerchantPageOther(merchant);
        return RestResult.success(merchants);
    }




    @ApiOperation(value = "导入商家列表信息")
    @PostMapping(value = "/importMerchantInfo")
    public RestResult importMerchantInfo(@RequestBody MerchantImportRequest merchantImportRequest){
        return mMerchantService.importMerchantInfo(merchantImportRequest.getMerchantList());
    }

    @ApiOperation(value = "通过商家id查询")
    @PostMapping(value = "/queryMerchantListByid")
    @Override
    public RestResult<List<MerchantRequest>> queryMerchantListByid(@RequestBody List<Long> merchantList){
        RestResult<List<MerchantRequest>> merchantPageResult = mMerchantService.queryMerchantListByid(merchantList);
        return merchantPageResult;
    }

    @Override
    @PostMapping(value = "/query")
    public List<MerchantResponse> query(@RequestBody MerchantRequest merchant) {
        return mMerchantService.queryBySelect(merchant);
    }

    @Override
    public RestResult<MerchantResponse> queryById(Long id) {
        MerchantResponse response = new MerchantResponse();
        Merchant merchant = mMerchantService.queryByPrimaryKey(id);
        BeanUtils.copyProperties(merchant, response);
        return RestResult.success(response);
    }

    @Override
    public List<JSONObject> getMerchantToSett() {
        List<JSONObject> list  = mMerchantService.getMerchantToSett();
        return list;
    }


    @ApiOperation(value = "通过商家CODE查询")
    @PostMapping(value = "/getByThirdMerchantCode")
    public RestResult<Merchant> getByThirdMerchantCode(@RequestBody String code){
        RestResult<Merchant> merchant = mMerchantService.getByThirdMerchantCode(code);
        return merchant;
    }

    @ApiOperation(value = "导入商家列表信息Excel")
    @PostMapping(value = "/importMerchantInfoByExcel")
    public RestResult importMerchantInfoByExcel(@RequestParam("file")MultipartFile file,@RequestParam("code")Long childcode
                                                ) throws IOException {
        return mMerchantService.importMerchantInfoByExcel(file,childcode);
    }

}
